`
https://leetcode.cn/problems/most-frequent-subtree-sum/
`

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var findFrequentTreeSum = function (root) {
  // 记录每个子树的元素和
  const map = {}
  // 记录子树元素和出现最多次的次数
  let maxCount = 0
  const res = []

  const traverse = (root) => {
    if (root === null) return 0

    const leftSum = traverse(root.left)
    const rightSum = traverse(root.right)

    // 计算以当前结点为树的子树元素和
    const curSum = root.val + leftSum + rightSum

    // 当钱子树元素和的出现次数+1
    map[curSum] = (map[curSum] || 0) + 1
    // 更新最大的出现次数
    maxCount = Math.max(map[curSum], maxCount)

    return curSum
  }

  traverse(root)

  // 获取所有次数为最大出现次数的结点值，放入结果返回
  for (const [key, val] of Object.entries(map)) {
    if (val === maxCount) {
      res.push(+key)
    }
  }

  return res
};